
import { MineItem } from "./MineItem";
import { GameManager } from "./GameManager";
import { ShopItemManager } from "./ShopItemManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property([cc.Prefab])
    itemPrefabs: cc.Prefab[] = []

    generateList: any[];

    prefabsByName;

    itemStat: any[];

    endExplodePaticle: cc.Prefab;

    onLoad() {
        this.prefabsByName = {}
        let that = this;
        this.itemPrefabs.forEach(function (v) {
            that.prefabsByName[v.name] = v;
        })
        ShopItemManager.Instance(ShopItemManager).bombCount = cc.sys.localStorage.getItem('bombCount') || 0;
        ShopItemManager.Instance(ShopItemManager).stoneValueUpCount = cc.sys.localStorage.getItem('stoneValueUpCount') || 0;
        ShopItemManager.Instance(ShopItemManager).refreshDisplay();
        this.generateItems();
        this.initGame();
        this.startTime();
    }

    generateItems() {

        let that = this;

        cc.loader.loadRes('MineItems', function (err, jsonAsset) {
            that.itemStat = jsonAsset.json;

            that.generateList = [{ "name": "gold-0-0", "count": 1 }, { "name": "diamond", "count": 1 }, { "name": "TNT", "count": 1 },
            { "name": "gold-0-5", "count": 1 }, { "name": "stone-0", "count": 1 }]
            that.generateList.forEach(function (v, k) {
                that.generateList[k].count = that.randomNum(1, 3);
            })
            let level = cc.sys.localStorage.getItem('level') || 1;
            that.generateList[1].count += Number(level);
            let isStrengthUp = ShopItemManager.Instance(ShopItemManager).isStrengthUp;
            that.generateList.forEach(function (v) {
                for (let i = 1; i <= v.count; i++) {
                    let tmp = cc.instantiate(that.prefabsByName[v.name]);
                    tmp.getComponent(MineItem).score = that.itemStat[v.name].score;
                    tmp.getComponent(MineItem).speed = isStrengthUp ? 100 : that.itemStat[v.name].speed;
                    tmp.parent = that.node;
                    let pos = that.randomXY();
                    tmp.setPosition(pos);
                }
            })
        });
    }


    moveMineCar() {
        let posX = this.node.width / 2 + GameManager.Instance(GameManager).mineCar.width / 2;
        GameManager.Instance(GameManager).playAnim("minerMove")
        cc.tween(GameManager.Instance(GameManager).mineCar).to(3, { position: cc.v2(posX, 500) })
            .call(() => { GameManager.Instance(GameManager).stopAnim() }).start()
    }

    reloadGame() {
        cc.game.resume();
        this.startTime();
        let that = this;
        //重载场景
        cc.director.loadScene('main', function () {
            GameManager.Instance(GameManager).hookItem = cc.find("minerCar/Hook/item");
            GameManager.Instance(GameManager).minerAnimation = cc.find("minerCar").getComponent(cc.Animation);
            cc.find("UI/dialog-background/button").on(cc.Node.EventType.TOUCH_START, that.reloadGame, that, true);
            GameManager.Instance(GameManager).shopPanel = cc.find("shop-panel");
            GameManager.Instance(GameManager).catchItem = null;
            GameManager.Instance(GameManager).endGamePanel = cc.find("UI/dialog-background");
            ShopItemManager.Instance(ShopItemManager).tipLabel = cc.find("shop-panel/shop-desk/tipLabel").getComponent(cc.Label);
        });
        clearInterval(GameManager.Instance(GameManager).timer);
        GameManager.Instance(GameManager).remainTime = 60;

    }

    initGame() {
        let that = this;
        GameManager.Instance(GameManager).catchItem = null;
        GameManager.Instance(GameManager).shopPanel = cc.find("shop-panel");
        GameManager.Instance(GameManager).hookItem = cc.find("minerCar/Hook/item");
        GameManager.Instance(GameManager).minerAnimation = cc.find("minerCar").getComponent(cc.Animation);
        cc.find("UI/dialog-background/button").on(cc.Node.EventType.TOUCH_START, that.reloadGame, that, true);
    }

    /**
     * 启动倒计时
     */
    startTime() {
        let manager = GameManager.Instance(GameManager);
        clearInterval(manager.timer);
        manager.timer = setInterval(() => {
            manager.remainTime--;
            if (manager.remainTime < 0) {
                manager.remainTime = 0;
            }
            manager.timeLabel.string = manager.remainTime.toString();
            if (manager.remainTime <= 0) {
                GameManager.Instance(GameManager).gameOver();
                clearInterval(manager.timer);
            };
        }, 1000);
    }


    /**
     * 随机坐标
     */
    randomXY() {
        let randX = this.randomNum(30, this.node.width - 100);
        let randY = this.randomNum(30, this.node.height - 100);
        return cc.v2(randX, randY);
    }


    /**
     * 产生随机整数，包含下限值，包括上限值
     * @param lower 
     * @param upper 
     */
    randomNum(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    }

    /**
     * 设置购买商品索引
     * @param event 
     * @param index 选中商品索引
     */
    setBuyItemIndex(event, index) {
        event.currentTarget.parent.children.forEach(function (v, k) {
            if (index == k) {
                cc.find('back', v).active = true;
            } else {
                cc.find('back', v).active = false;
            }
        })
        let manager = ShopItemManager.Instance(ShopItemManager);
        manager.buyItemIndex = index;
        manager.tipLabel.string = manager.itemDescText[index];
    }

    buyItem() {
        ShopItemManager.Instance(ShopItemManager).buyItem();
    }
}
